<?php 
defined( '_VALID_MOS' ) or die( 'Restricted access' );

global $mosConfig_lang;
if (file_exists( $mosConfig_absolute_path.'/components/com_jcs/languages/'.$mosConfig_lang.'.php' ))
    include_once( $mosConfig_absolute_path.'/components/com_jcs/languages/'.$mosConfig_lang.'.php' );
else
    require_once( $mosConfig_absolute_path.'/components/com_jcs/languages/english.php' );

if(!class_exists('JEConfig'))
    require_once( $mosConfig_absolute_path.'/administrator/components/com_jcs/joomlaequipment.config.php');

function jcsMakeSubscr($user, $val, $publish = 1, $url)
{
    global $database, $my, $mosConfig_mailfrom, $mosConfig_fromname, $mosConfig_sitename;
    if(!$val['gateway_id']) $val['gateway_id'] = date("m-d")."-".$val['id'];
    //error_log("Start creating Subscription\n",3, 'log.txt');
    // find if we already have this subscription
    if($val['user'] > 0) $user = $val['user'];
    if(!$user) mosRedirect($url);
    //error_log("Continue creating Subscription\n",3, 'log.txt');
    
    $url .= '&sid='.$val['id'];
    if($row->adwords) { $url .= '&adwords='.$val['id'];}
    
    
    if($val['gateway_id'])
    {
        $sql = "SELECT id FROM #__jcs_user_subscr WHERE gateway_id = '{$val[gateway_id]}' AND user_id = '{$user}'";
        $database->setQuery($sql);
        $gsid = $database->loadResult();
        if($gsid > 0) mosRedirect($url);
    }
    
    $sql = "SELECT id FROM #__jcs_user_subscr WHERE DATE(`created`) = CURDATE() AND gateway_id = '{$val[gateway_id]}' AND user_id = '{$user}' AND subscription_id = '{$val[id]}'";
    $database->setQuery($sql);
    $subd = $database->loadResult();
    if($subd) mosRedirect($url);

    $sql = "SELECT id, alert_admin, name, days, price, time_limit, days_type, adwords, gid, usertype FROM #__jcs_plans WHERE id = $val[id]";
    $database->setQuery( $sql );
    $rows = $database->loadObjectList();
    $row  = $rows[0];
    
    // save usertype to usetype column
    if($row->gid > 0){
        $query = "SELECT lft FROM  #__core_acl_aro_groups where group_id = '{$row->gid}'";
        $database->setQuery( $query );
        $newl = $database->loadResult();
        
        $query = "
          SELECT g.lft FROM #__core_acl_aro_groups AS g 
       LEFT JOIN #__users AS u ON u.gid = g.group_id 
           WHERE u.id = '{$user}'";
        $database->setQuery( $query );
        $oldl = $database->loadResult();
    
        if($newl > $oldl){ 
            $query = "UPDATE #__users SET gid = '{$row->gid}', usertype = '{$row->usertype}' WHERE id  = '{$user}'";
            $database->setQuery( $query );
            $database->query();
            // update the ACL
            $query = "SELECT aro_id"
            . "\n FROM #__core_acl_aro"
            . "\n WHERE value = " . (int) $user
            ;
            $database->setQuery( $query );
            $aro_id = $database->loadResult();
            
            $query = "UPDATE #__core_acl_groups_aro_map"
            . "\n SET group_id = $row->gid"
            . "\n WHERE aro_id = $aro_id"
            ;
            $database->setQuery( $query );
            $database->query() or die( $database->stderr() );
        }
    }
    $sql = "
        SELECT id, extime, IF(NOW() > extime , 1, 0) AS expire 
          FROM #__jcs_user_subscr
         WHERE user_id = $user 
           AND subscription_id = {$val[id]}
      ORDER BY extime DESC
        ";
    $database->setQuery( $sql );
    $rows = $database->loadObjectList();
    //print_r($rows);
    //var_dump((count($rows) == 0) || ($rows[0]->expire));
    //return;
    if((count($rows) == 0) || ($rows[0]->expire) || ($rows[0]->published == 0) || ($row->time_limit > 0))
    {
        $date = ' NOW() ';
        //$sdate = ' NOW() ';
    }
    else
    {
        $date = " '{$rows[0]->extime}' ";
        //$sdate = " '{$rows[0]->extime}' ";
    }
    
    
    //echo $row->days_type;
    switch($row->days_type)
    {
        case "weeks";
           $days = $row->days * 7;
        break;
        case "months";
           $days = $row->days * 31;
        break;
        case "years";
           $days = $row->days * 365;
        break;
        default:
           $days = $row->days;
    }
   if($val['price'] > 0) $row->price = $val['price'];
   $sql  = "
       INSERT INTO #__jcs_user_subscr 
       (`user_id`, `subscription_id`, `ctime`, `extime`, `price`, 
       `published`, `access_limit`, `gateway`, `gateway_id`, `created`) 
       VALUES 
       ('{$user}', '{$val[id]}', {$date}, DATE_ADD({$date}, INTERVAL $days DAY), 
       '$row->price', '$publish', '$row->time_limit', '{$val[gateway]}', '{$val[gateway_id]}', NOW() ) ";
      
    //error_log("$sql\n",3, 'log.txt');
    //echo $sql;
    //return;
    $database->setQuery( $sql );
    $database->query();
    //error_log($database->stderr()."\n",3, 'log.txt');
    $sid = $database->insertid();
    //echo $database->stderr();
    
    if(($publish > 0) && file_exists($GLOBALS['mosConfig_absolute_path'] . '/components/com_idevaffiliate/sale.php'))
    {
        $idevtotal     = $row->price;
        $idev_paypal_1 = $row->price;
        $idev_paypal_2 = 'paypal'.$val['gateway_id'].'.'.$sid;
        
        include ($GLOBALS['mosConfig_absolute_path'] . '/components/com_idevaffiliate/sale.php');
    }
    
    if($row->alert_admin)
    {
        // check if Global Config `mailfrom` and `fromname` values exist
        if ($mosConfig_mailfrom != '' && $mosConfig_fromname != '') {
            $adminName2 	= $mosConfig_fromname;
            $adminEmail2 	= $mosConfig_mailfrom;
        } else {
        // use email address and name of first superadmin for use in email sent to user
            $query = "SELECT name, email"
            . "\n FROM #__users"
            . "\n WHERE LOWER( usertype ) = 'superadministrator'"
            . "\n OR LOWER( usertype ) = 'super administrator'"
            ;
            $database->setQuery( $query );
            $rows = $database->loadObjectList();
            $row2 			= $rows[0];
            
            $adminName2 	= $row2->name;
            $adminEmail2 	= $row2->email;
        }
        
        
        
        $subject 	= "$mosConfig_sitename:: New Subscription";
        
        $message = "
          Hello $adminName2,
          
          User [{$user}] have been subscribed to subscription plan  [{$row->id}] {$row->name}. 
          
          subscription ID: {$sid}
          Gateway: {$val[gateway]}
          Gateway Order ID: {$val[gateway_id]}
          
          JContentSubscription Robot. 
        ";
        
        
        
        $message = html_entity_decode($message, ENT_QUOTES);
        
        //$hdr = 'From: robot@'.$_SERVER['SERVER_NAME']."\r\n"
       //."Reply-To: no-replay@{$_SERVER[SERVER_NAME]}\r\n" 
       //."X-Mailer: PHP/" . phpversion()."\r\n";
        // Send email to user
        //mail($adminEmail2, $subject, $message, $hdr);
        //echo $adminEmail2;exit;
        //mosMail($adminEmail2, $adminName2, $adminEmail2, );
        mosMail( $adminEmail2, $adminName2, $adminEmail2, $subject, $message);
    }
    
    $email 		= $my->email;
    jcsAlertUser($email, $my->name, $row->name, 'reg', $publish);
    
    
    mosRedirect($url);
    //, 'User Subscription Created!');
    //if($admin) mosRedirect('index2.php?option=com_jcs&task=usub' ,'User Subscription Created!');
    //else mosRedirect('index.php?option=com_jcs&' ,'User Subscription Created!');
    
}

// $type may be reg or exp. This sends alerts on registration and expiration.
function jcsAlertUser($email, $name, $subname, $type, $publish = 1)
{
    global $mosConfig_mailfrom, $mosConfig_fromname, $database, $my;
    global $mosConfig_sitename, $mosConfig_live_site;
    
    if ($mosConfig_mailfrom != '' && $mosConfig_fromname != '') {
        $adminName2 	= $mosConfig_fromname;
        $adminEmail2 	= $mosConfig_mailfrom;
    } else {
    // use email address and name of first superadmin for use in email sent to user
        $query = "SELECT name, email"
        . "\n FROM #__users"
        . "\n WHERE LOWER( usertype ) = 'superadministrator'"
        . "\n OR LOWER( usertype ) = 'super administrator'"
        ;
        $database->setQuery( $query );
        $rows = $database->loadObjectList();
        $row2 			= $rows[0];
        
        $adminName2 	= $row2->name;
        $adminEmail2 	= $row2->email;
    }
    
    if($type == 'reg')
    {
        $subject = sprintf(JCS_ALERT_USER_SUBSCR_S, $mosConfig_sitename);
        if($publish)
        {
            $message = sprintf(JCS_ALERT_USER_SUBSCR, $name, $subname, $mosConfig_sitename, $mosConfig_live_site);
        }
        else
        {
            $message = sprintf(JCS_ALERT_USER_SUBSCR_F, $name, $subname, $mosConfig_sitename, $adminEmail2);
        }
           
    }
    else if($type == 'exp')
    {
        $subject = sprintf(JCS_ALERT_USER_EXPIRE_S, $mosConfig_sitename, JEConfig::get('general.expire'));
        $message = sprintf(JCS_ALERT_USER_EXPIRE, $name, $mosConfig_sitename, $subname,  $mosConfig_live_site, JEConfig::get('general.expire'), $mosConfig_live_site);   
    }
    else if($type == 'subscr')
    {
    
    }
    //echo $subject.$message;
    //exit;
    //$message = html_entity_decode($message, ENT_QUOTES);
    //mail($email, $subject, $message, 
    //    "From: {$mosConfig_sitename}<{$adminEmail2}>\r\n"
    //   ."Reply-To: {$adminName2}<{$adminEmail2}\r\n" 
    //   ."X-Mailer: PHP/" . phpversion());
    //mosMail($adminEmail2, $adminName2, $email, $subject, $message);
   mosMail( $adminEmail2, $adminName2, $email, $subject, $message);
}
function jcsManage($uid = NULL)
{
    global $database, $option, $mainframe, $mosConfig_absolute_path,$mosConfig_live_site;
    
    $limit      = intval( $mainframe->getUserStateFromRequest( "viewlistlimit", 'limit', $mosConfig_list_limit ) );
    $limitstart = intval( $mainframe->getUserStateFromRequest( "view{$option}limitstart", 'limitstart', 0 ) );
    
    $user_id = intval(mosGetParam( $_REQUEST, 'suser_id', false)) ;
    $subscription_id = intval(mosGetParam( $_REQUEST, 'ssubscription_id', false)) ;
    $state = intval(mosGetParam( $_REQUEST, 'state', 10)) ;
    
    if($user_id > 0 ) $where .= " AND u.user_id = {$user_id} ";
    if($subscription_id > 0 ) $where .= " AND u.subscription_id = {$subscription_id} ";
    if($state == 0 ) $where .= " AND u.published = 0 "; 
    if($state == 1 ) $where .= " AND u.published = 1 ";
    
    $sql = "
    SELECT u.id, u.gateway, u.gateway_id, u.access_limit, u.published, u.access_count,  u.price, n.name AS uname, n.email, n.id AS uid, 
           DATE_FORMAT(u.ctime, '%d, %b %Y') AS ctime, 
           DATE_FORMAT(u.extime,'%d, %b %Y' ) AS extime, s.name, 
           (TO_DAYS(u.extime) - TO_DAYS(NOW())) as days, s.id AS sid 
      FROM #__jcs_user_subscr AS u 
 LEFT JOIN #__jcs_plans AS s ON s.id = u.subscription_id  
 LEFT JOIN #__users AS n ON n.id = u.user_id  
     WHERE 1 {$where}". 
     ($uid ? " AND u.user_id = {$uid} " : NULL)
     ."ORDER BY u.ctime DESC";
    
    //echo $sql;
    
    $database->setQuery( $sql );
    $total = $database->loadObjectList();

    require_once( $mosConfig_absolute_path . '/administrator/includes/pageNavigation.php' );
    $pageNav = new mosPageNav( count($total), $limitstart, $limit );

    $database->setQuery( $sql, $pageNav->limitstart, $pageNav->limit );
    $rows = $database->loadObjectList();
    mosCommonHTML::loadOverlib();
    include dirname( __FILE__ )."/views/list.user.sub.html.php";
    //jcsMangeHtml($rows, $pageNav);
}

function jcsView($id = 0)
{
    global $database, $mainframe, $mosConfig_list_limit, 
           $mosConfig_absolute_path, $option;
    
    $limit      = intval( $mainframe->getUserStateFromRequest( "viewlistlimit", 'limit', $mosConfig_list_limit ) );
    $limitstart = intval( $mainframe->getUserStateFromRequest( "view{$option}limitstart", 'limitstart', 0 ) );
    
    $query = "SELECT COUNT(*) FROM #__jcs_plans";
    $database->setQuery( $query );
    $total = $database->loadResult();
    
    require_once( $mosConfig_absolute_path . '/administrator/includes/pageNavigation.php' );
    $pageNav = new mosPageNav( $total, $limitstart, $limit );

    $query = "SELECT s.*, count(u.id) as subscr, c.id AS ctid, c.name AS cname FROM #__jcs_plans AS s 
  LEFT JOIN #__jcs_user_subscr AS u ON u.subscription_id = s.id 
  LEFT JOIN #__categories AS c ON c.id = s.catid 
    GROUP BY s.id 
    ORDER BY c.ordering ASC, s.ordering ASC";
    //$query = "SELECT s.* FROM #__jcs_plans AS s ";
    $database->setQuery( $query, $pageNav->limitstart, $pageNav->limit );
    $rows = $database->loadObjectList();
    
    include dirname( __FILE__ )."/views/list.sub.html.php";
    //jcsViewSubscriptionHtml($rows, $pageNav);
}
function jcsPublish($cid, $task)
{
    global $database;
    if (count( $cid ) < 1) { return; }
    
    $cids = implode( ',', $cid );
    
    $task == 'publish' ? $p = 1 : $p = 0;
    $query = "UPDATE #__jcs_plans SET published = ".intval($p)." WHERE id IN ( $cids )";
    $database->setQuery( $query );
    $database->query();
}	
function jcsUPublish($cid, $task)
{
    global $database;
    if (count( $cid ) < 1) { return; }
    
    $cids = implode( ',', $cid );
    
    $task == 'upublish' ? $p = 1 : $p = 0;
    $query = "UPDATE #__jcs_user_subscr SET published = ".intval($p)." WHERE id IN ( $cids )";
    $database->setQuery( $query );
    $database->query();
}	

function jcsAdWordsCode($id)
{
    global $database;
    $sql = "SELECT adwords FROM #__jcs_plans WHERE id = $id";
    $database->setQuery( $sql );
    return $database->loadResult();
}

function jcsPublishedProcessing( &$row, $i ) {
		$img 	= $row->published ? 'publish_g.png' : 'publish_x.png';
		$task 	= $row->published ? 'uunpublish' : 'upublish';
		$alt 	= $row->published ? 'Published' : 'Unpublished';
		$action	= $row->published ? 'Unpublish Item' : 'Publish item';

		$href = '
		<a href="javascript: void(0);" onclick="return listItemTask(\'cb'. $i .'\',\''. $task .'\')" title="'. $action .'">
		<img src="images/'. $img .'" border="0" alt="'. $alt .'" />
		</a>'
		;

		return $href;
	}
  
   ?>
